const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors'); // 引入cors中间件

const app = express();
const PORT = process.env.PORT || 3333;

// 连接MongoDB
mongoose.connect('mongodb://localhost:27017/loginapp', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('MongoDB connected'))
    .catch(err => console.error('MongoDB connection error:', err));

app.use(bodyParser.json());// 使用body-parser中间件,解析json格式
app.use(cors()); // 使用cors中间件

// 定义数据模型
const UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    notes: [{
        text: String,
        createdAt: { type: Date, default: Date.now }
    }]
});

const User = mongoose.model('User', UserSchema);

// 注册用户
app.post('/register', async (req, res) => {
    const { username, password } = req.body;
    console.log(`Registering user: ${username}`);
    const user = new User({ username, password });
    try {
        await user.save();
        console.log(`User registered: ${username}`);
        res.status(201).send(user);
    } catch (err) {
        console.error('Error registering user:', err);
        res.status(500).send({ message: 'Error registering user' });
    }
});

// 用户登录
app.post('/login', async (req, res) => {
    const { username, password } = req.body;
    console.log(`Logging in user: ${username}`);
    try {
        const user = await User.findOne({ username, password });
        if (user) {
            console.log(`User logged in: ${username}`);
            res.status(200).send(user);
        } else {
            console.log(`Invalid credentials for user: ${username}`);
            res.status(401).send({ message: 'Invalid credentials' });
        }
    } catch (err) {
        console.error('Error logging in user:', err);
        res.status(500).send({ message: 'Error logging in user' });
    }
});

// 添加笔记
app.post('/notes', async (req, res) => {
    const { username, text } = req.body;
    console.log(`Adding note for user: ${username}`);
    try {
        const user = await User.findOne({ username });
        if (user) {
            user.notes.push({ text });
            await user.save();
            console.log(`Note added for user: ${username}`);
            res.status(201).send(user);
        } else {
            console.log(`User not found: ${username}`);
            res.status(404).send({ message: 'User not found' });
        }
    } catch (err) {
        console.error('Error adding note:', err);
        res.status(500).send({ message: 'Error adding note' });
    }
});

// 获取笔记
app.get('/notes/:username', async (req, res) => {
    const { username } = req.params;
    console.log(`Fetching notes for user: ${username}`);
    try {
        const user = await User.findOne({ username });
        if (user) {
            console.log(`Notes fetched for user: ${username}`);
            res.status(200).send(user.notes);
        } else {
            console.log(`User not found: ${username}`);
            res.status(404).send({ message: 'User not found' });
        }
    } catch (err) {
        console.error('Error fetching notes:', err);
        res.status(500).send({ message: 'Error fetching notes' });
    }
});

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});